﻿using System;
using System.Runtime.CompilerServices;
using SolaceSystems.Solclient.Messaging;
using Unity.Connections;
using Unity.Credentials;


namespace Unity.Solace
{
    public class UnitySolaceConsumer : IUnityConsumer
    {
        private IContext _context;
        private ISession _session;
        private readonly UnitySolaceCredentials _credentials;
        private readonly IUnityCallback _callback;

        public UnitySolaceConsumer(UnitySolaceCredentials credentials, IUnityCallback callback)
        {
            _credentials = credentials;
            _callback = callback;
        }

        private void HandleMessage(object source, MessageEventArgs args)
        {
            IMessage message = args.Message;
            _callback.Handle(message.BinaryAttachment);
            message.Dispose();
        }
        
        public bool Connect(IUnityCredentials credentials)
        {
            try
            {
                _context = _credentials.GetContext();
                _session = _context.CreateSession(
                    _credentials.GetSessionProperties(),
                    HandleMessage, null
                );
                ReturnCode returnCode = _session.Connect();
                if (returnCode == ReturnCode.SOLCLIENT_OK)
                {
                    returnCode = _session.Subscribe(
                        ContextFactory.Instance.CreateTopic(_credentials.GetTopic()),
                        true);
                }

                return returnCode == ReturnCode.SOLCLIENT_OK;

            }
            catch (Exception exception)
            {
                
            }

            return false;
        }
        
        public void Close()
        {
            if (_session != null)
            {
                _session.Disconnect();
                _session.Dispose();
            }

            if (_context != null)
            {
                _context.Dispose();
            }
        }

        public byte[] Pull(int timeout)
        {
            throw new NotImplementedException();
        }
        
        public void Dispose()
        {
            throw new NotImplementedException();
        }
    }
}